<template>
  <div class="control-rule-page">
    <!-- 卡片1: 接入控制模式 -->
    <div class="mode-card">
      <div class="mode-header">
        <h2 class="card-title">接入控制模式</h2>
      </div>
      <div class="mode-container">
        <div
          class="mode-box blacklist"
          :class="{ active: currentMode === ControlRuleMode.BLACKLIST }"
          @click="handleModeChange(ControlRuleMode.BLACKLIST)"
        >
          <h3>黑名单模式</h3>
          <p>默认允许所有终端接入系统，仅限制黑名单中的设备无法接入。适用于大多数设备可信任的场景。</p>
        </div>
        <div
          class="mode-box whitelist"
          :class="{ active: currentMode === ControlRuleMode.WHITELIST }"
          @click="handleModeChange(ControlRuleMode.WHITELIST)"
        >
          <h3>白名单模式</h3>
          <p>默认禁止所有终端接入系统，仅允许白名单中的终端接入。适用于高安全性要求的场景。</p>
        </div>
      </div>
    </div>

    <!-- 卡片2: 列表操作和数据表格 -->
    <div class="table-card">
      <!-- Tab 切换 -->
      <div class="custom-tabs">
        <div
          class="tab-item"
          :class="{ active: currentRuleType === 'DEVICE_ID' }"
          @click="handleTabChange('DEVICE_ID')"
        >
          终端ID{{ currentMode === ControlRuleMode.BLACKLIST ? '黑名单' : '白名单' }}
        </div>
        <div
          class="tab-item"
          :class="{ active: currentRuleType === 'DEVICE_IP' }"
          @click="handleTabChange('DEVICE_IP')"
        >
          终端IP{{ currentMode === ControlRuleMode.BLACKLIST ? '黑名单' : '白名单' }}
        </div>
      </div>

      <!-- 数据表格 -->
      <BasicTable @register="registerTable">
        <template #tableTitle>
          <div class="space-x-2">
            <a-button type="primary" @click="handleForm({})">
              <Icon icon="i-fluent:add-12-filled" /> 添加规则
            </a-button>
            <a-input
              v-model:value="searchText"
              placeholder="输入搜索内容"
              allow-clear
              @change="reload"
              style="width: 240px"
            >
              <template #suffix>
                <Icon icon="ant-design:search-outlined" />
              </template>
            </a-input>
          </div>
        </template>
        <template #mode="{ record }">
          <Tag :color="record.mode === ControlRuleMode.BLACKLIST ? 'red' : 'green'">
            {{ record.mode === ControlRuleMode.BLACKLIST ? '黑名单' : '白名单' }}
          </Tag>
        </template>
      </BasicTable>
    </div>
    <InputForm @register="registerFormModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts">
  export default defineComponent({
    name: 'ViewsTbControlRuleList',
  });
</script>

<script lang="ts" setup>
  import { defineComponent, ref } from 'vue';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { Tag } from 'ant-design-vue';
  import { Icon } from '/@/components/Icon';
  import InputForm from './form.vue';
  import {
    getControlRuleList,
    deleteControlRule,
    ControlRule,
    ControlRuleType,
    ControlRuleMode,
  } from '/@/api/tb/controlRule';

  const { createConfirm, showMessage } = useMessage();
  const [registerFormModal, { openModal: openFormModal }] = useModal();

  const currentMode = ref<ControlRuleMode>(ControlRuleMode.BLACKLIST);
  const currentRuleType = ref<ControlRuleType>(ControlRuleType.DEVICE_IP);
  const searchText = ref('');

  const tableColumns: BasicColumn[] = [
    {
      title: '规则类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      customRender: ({ text }) => {
        return text === 'DEVICE_ID' ? '设备ID' : 'IP地址';
      },
    },
    {
      title: '规则内容',
      dataIndex: 'value',
      key: 'value',
      align: 'left',
    },
    {
      title: '模式',
      dataIndex: 'mode',
      key: 'mode',
      width: 120,
      slot: 'mode',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: 200,
    },
  ];

  const actionColumn: BasicColumn = {
    width: 160,
    actions: (record: Recordable) => [
      {
        icon: 'ant-design:edit-outlined',
        title: '编辑',
        onClick: handleForm.bind(this, { ...record }),
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: '删除',
        onClick: handleDelete.bind(this, { ...record }),
      },
    ],
  };

  const [registerTable, { reload, setProps }] = useTable({
    rowKey: (record) => record.id.id,
    api: fetchRuleList,
    beforeFetch: wrapFetchParams,
    defSort: { sortProperty: 'createdTime', sortOrder: 'DESC' },
    columns: tableColumns,
    actionColumn: actionColumn,
    showTableSetting: false,
    useSearchForm: false,
    canResize: false,
    pagination: {
      pageSize: 10,
    },
  });

  function wrapFetchParams(param: any) {
    return {
      ...param,
      mode: currentMode.value,
      type: currentRuleType.value,
      textSearch: searchText.value,
    };
  }

  async function fetchRuleList(param: any) {
    return await getControlRuleList(param);
  }

  function handleModeChange(mode: ControlRuleMode) {
    currentMode.value = mode;
    reload();
  }

  function handleTabChange(type: string) {
    currentRuleType.value = type as ControlRuleType;
    const valueColumn = tableColumns.find((col) => col.dataIndex === 'value');
    if (valueColumn) {
      valueColumn.title = type === 'DEVICE_ID' ? '终端ID' : '终端IP';
    }
    setProps({ columns: tableColumns });
    reload();
  }

  function handleForm(record: Recordable) {
    openFormModal(true, {
      ...record,
      defaultType: currentRuleType.value,
      defaultMode: currentMode.value,
    });
  }

  function handleDelete(record: Recordable) {
    const ruleTypeName = record.type === 'DEVICE_ID' ? '设备ID' : 'IP地址';
    const modeName = record.mode === ControlRuleMode.BLACKLIST ? '黑名单' : '白名单';

    createConfirm({
      iconType: 'error',
      title: `确定删除${modeName}规则吗？`,
      content: `规则类型：${ruleTypeName}，规则内容：${record.value}`,
      centered: false,
      okText: '删除',
      okButtonProps: {
        type: 'primary',
        danger: true,
      },
      onOk: async () => {
        const ruleId = record.id?.id ?? record.id;
        if (!ruleId) {
          showMessage('删除规则失败：缺少规则ID', 'error');
          return;
        }
        try {
          await deleteControlRule(ruleId);
          showMessage('规则已成功删除', 'success');
          reload();
        } catch (error: any) {
          const errorMessage = error?.message || error?.data?.message || '未知错误';
          showMessage(`删除规则失败: ${errorMessage}`, 'error');
        }
      },
    });
  }

  function handleSuccess() {
    reload();
  }
</script>

<style lang="less" scoped>
  .control-rule-page {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 80px);
    overflow: hidden;

    .mode-card {
      background-color: #ffffff;
      padding: 12px;
      border-radius: 5px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      margin-bottom: 1.5rem;
    }

    .table-card {
      flex: 1;
      display: flex;
      flex-direction: column;
      background-color: #ffffff;
      padding: 5px 2px 5px 7px;
      border-radius: 5px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      overflow: hidden;

      :deep(.vben-basic-table) {
        display: flex;
        flex-direction: column;
        height: 100%;
        overflow: hidden;

        .ant-table-wrapper {
          flex: 1;
          overflow: hidden;
          display: flex;
          flex-direction: column;

          .ant-spin-nested-loading {
            flex: 1;
            overflow: hidden;
            display: flex;
            flex-direction: column;

            .ant-spin-container {
              flex: 1;
              overflow: hidden;
              display: flex;
              flex-direction: column;

              .ant-table {
                flex: 1;
                overflow: hidden;
                display: flex;
                flex-direction: column;

                .ant-table-container {
                  flex: 1;
                  overflow: auto;
                }
              }
            }
          }
        }
      }
    }

    .mode-header {
      margin-bottom: 0.5rem;
    }

    .card-title {
      font-size: 1.125rem;
      font-weight: 700;
      margin: 0;
    }

    .mode-container {
      display: flex;
      gap: 1rem;
    }

    .mode-box {
      flex: 1;
      border: 1px solid #dee2e6;
      border-radius: 8px;
      padding: 1.5rem;
      cursor: pointer;
      transition: all 0.2s;

      &:hover {
        border-color: #a0a0a0;
      }

      &.active {
        border-color: #1890ff;
        box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.25);
      }

      h3 {
        margin: 0 0 0.5rem 0;
        font-size: 1.1rem;
        font-weight: 600;
        display: flex;
        align-items: center;

        &::before {
          display: inline-block;
          width: 24px;
          height: 24px;
          margin-right: 0.5rem;
          font-size: 1.2rem;
          line-height: 24px;
          text-align: center;
          border-radius: 50%;
        }
      }

      &.blacklist h3::before {
        content: '🚫';
        background-color: #fdf0f1;
      }

      &.whitelist h3::before {
        content: '✅';
        background-color: #eef7f0;
      }

      &.active.blacklist h3::before {
        background-color: #ffe8e9;
      }

      p {
        font-size: 0.875rem;
        color: #6c757d;
        margin: 0;
        line-height: 1.5;
      }
    }

    .custom-tabs {
      display: flex;
      border-bottom: 1px solid #dee2e6;
      margin-bottom: 0.5rem;

      .tab-item {
        padding: 0.75rem 1rem;
        cursor: pointer;
        font-size: 1rem;
        color: #6c757d;
        border-bottom: 2px solid transparent;
        margin-bottom: -1px;
        transition: all 0.2s;

        &:hover {
          color: #1890ff;
        }

        &.active {
          color: #1890ff;
          border-bottom-color: #1890ff;
          font-weight: 500;
        }
      }
    }
  }
</style>
